﻿<p class="bold large">Write the method reverseString that returns the reversed form of a String</p>
<p class="italic">Note: You can either write a recursive or iterative method. Examples of both will be provided in the 'Possible Solution' section</p>
<p>If "Code" were passed in then "edoC" would be returned</p>
<p>If "" were passed in then "" would be returned</p>
<p>If null were passed in then null should be returned</p>
<div class="practiceAccordion">
    <h3>Hints</h3>
    <div>
        <ul>
            <li>First check if the String is null and return null accordingly to avoid dealing with it later</li>
            <li>Use the charAt method in the String class to get specific characters of a String</li>
            <li>Use the substring method to cut a String as necessary</li>
            <li>For the iterative method create an empty string that characters can be added to</li>
            <li>For the recursive method have your second base case to check if the String is empty</li>
            <li>For the iterative method use a loop to start at the back of the String and add characters to your String</li>
            <li>For the recursive method (after passing the first two base cases) return the last character and run the method on the String 
            again excluding the last character (you are progressively cutting out the last letter every time)</li>
        </ul>
    </div>
    <h3>Possible Solution (Iterative)</h3>
<p class="format code">public static String reverseString(String str) {
    if(str == null) {
        return null;
    }
        
    String reversed = "";
    for(int i = str.length() - 1; i >= 0; i--) {
        reversed += str.charAt(i);
    }
        
    return reversed;
}</p>
    <h3>Possible Solution (Recursive)</h3>
<p class="format code">public static String reverseString(String str) {
    if(str == null) {
        return null;
    }
    else if(str.equals("")) {
        return "";
    }
    else {
        return str.charAt(str.length() - 1) + recurReverseString(str.substring(0, str.length() - 1));
    }
}</p>
</div>
<a href="#practiceTop">Back to top</a>